package com.suixun.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suixun.dao.DeviceReserveMapper;
import com.suixun.dao.DevicelistMapper;
import com.suixun.dao.PurchaseDeliveryMapper;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.StdDeviceinfoMapper;
import com.suixun.dao.StdIotDeviceMapper;
import com.suixun.dao.StdSimidauthMapper;
import com.suixun.dao.devicemanage.DeviceInitServiceDAO;
import com.suixun.dao.devicemanage.DeviceServiceDAO;
import com.suixun.dao.model.PageGrid;
import com.suixun.dao.model.PageQueryModel;
import com.suixun.entity.DeviceInfo;
import com.suixun.entity.DeviceReserve;
import com.suixun.entity.DeviceReserveExample;
import com.suixun.entity.Devicelist;
import com.suixun.entity.DevicelistExample;
import com.suixun.entity.PurchaseDeliveryExample;
import com.suixun.entity.Schoolinfo;
import com.suixun.entity.SchoolinfoExample;
import com.suixun.entity.StdDeviceinfo;
import com.suixun.entity.StdDeviceinfoExample;
import com.suixun.entity.StdIotDevice;
import com.suixun.entity.StdIotDeviceExample;
import com.suixun.entity.StdSimidauthExample;
import com.suixun.entity.ext.ExtDeviceReserve;
import com.suixun.entity.form.ParamForm;
import com.suixun.entity.page.PageModel;
import com.suixun.exception.OpServiceException;
import com.suixun.service.DeviceInitService;
import com.suixun.service.DevicePriceService;
import com.suixun.service.common.CommonService;
import com.suixun.util.BeanUtil;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.ExcelUtil;
import com.suixun.util.OpUtil;
import com.suixun.util.RegexUtil;
import com.suixun.util.StringUtil;
import com.suixun.util.Utils;
import com.suixun.vo.DeviceVO;

@Service
public class DeviceInitServiceImpl implements DeviceInitService {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private DeviceInitServiceDAO deviceInitdao;
	@Resource
	private DeviceServiceDAO devicedao;
	@Resource
	private DevicelistMapper devicelistMapper;
	@Resource
	private DeviceReserveMapper deviceReserveMapper;
	@Resource
	private SchoolinfoMapper schoolinfoMapper;
	@Resource
	private CommonService commonService;
	@Resource
	private StdSimidauthMapper stdSimidauthMapper;
	@Resource
	private StdIotDeviceMapper stdIotDeviceMapper;
	@Resource
	private PurchaseDeliveryMapper purchaseDeliveryMapper;
	@Resource
	private DevicePriceService devicePriceService;
	@Resource
	private StdDeviceinfoMapper stdDeviceinfoMapper;

	private final static String failReason = "入库失败，原因：第%d行%s";

	// 查询某个设备明细
	@Override
	public DeviceInfo queryDeviceByName(ParamForm paramForm) {
		if (StringUtil.isBlank(paramForm.getImei()))
			return null;
		DeviceInfo device = new DeviceInfo();
		device.setImei(paramForm.getImei());
		DeviceInfo batch = deviceInitdao.queryDeviceByName(device);
		return batch;
	}

	// 查询某个设备明细
	@Override
	public DeviceInfo queryDeviceByID(DeviceInfo paramForm) {
		if (paramForm.getId() == null)
			return null;
		DeviceInfo batch = deviceInitdao.queryDeviceByID(paramForm);
		return batch;
	}

	// 查询该设备已经被使用的数量
	@Override
	public int queryUsedDeviceCounts(DeviceInfo paramForm) {
		if (paramForm.getId() == null)
			return -1;
		return deviceInitdao.queryUsedDeviceCounts(paramForm);
	}

	// 分页查询设备列表
	@Override
	public PageModel<DeviceInfo> queryDeviceInitlistPage(ParamForm paramForm) {

		PageModel<DeviceInfo> pageModel = new PageModel<DeviceInfo>();
		if (StringUtil.isNotEmpty(paramForm.getImei())) {
			pageModel.getQueryparam().put("imei", "%" + paramForm.getImei() + "%");
		}
		if (StringUtil.isNotEmpty(paramForm.getBatchid())) {
			pageModel.getQueryparam().put("batchid", paramForm.getBatchid());
		}
		if (StringUtil.isNotEmpty(paramForm.getStatus())) {
			pageModel.getQueryparam().put("status", paramForm.getStatus());
		}
		if (StringUtil.isNotEmpty(paramForm.getSchoolname())) {
			pageModel.getQueryparam().put("schoolname", paramForm.getSchoolname());
		}

		if (StringUtil.isNotEmpty(paramForm.getPagecount())) {
			pageModel.setPagesize(Integer.parseInt(paramForm.getPagecount()));
		}

		String showType = paramForm.getShowtype();
		// 按箱号
		if ("2".equals(showType)) {
			Integer totleRows = deviceInitdao.countRowsByBox(pageModel);
			pageModel.setTotlepage(totleRows);
			if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
				pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
			}
			List<DeviceInfo> devicelist = deviceInitdao.queryDeviceInitlistPageByBox(pageModel);
			pageModel.setQueryresult(devicelist);

			Integer boxRows = deviceInitdao.countBoxRows(pageModel);
			pageModel.getQueryparam().put("boxRows", boxRows);
		} else {
			List<DeviceInfo> devicelist = new LinkedList<>();
			if (null == paramForm.getType() || "1".equals(paramForm.getType())) {
				Integer totleRows = deviceInitdao.countRows(pageModel);
				pageModel.setTotlepage(totleRows);
				if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
					pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
				}
				devicelist = deviceInitdao.queryDeviceInitlistPage(pageModel);
			} else {
				if ("2".equals(paramForm.getType())) {
					pageModel.getQueryparam().put("factory", Constant.Device.SAIFENG);
				} else if ("3".equals(paramForm.getType())) {
					if (StringUtil.isEmpty(paramForm.getImei())) {
						pageModel.getQueryparam().put("imei", StringUtil.append("8888"));
					}
				} else if ("4".equals(paramForm.getType())) {
					if (StringUtil.isEmpty(paramForm.getImei())) {
						pageModel.getQueryparam().put("imei", StringUtil.append("9999"));
					}
				}
				Integer totleRows = devicedao.countRows(pageModel);
				pageModel.setTotlepage(totleRows);
				if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
					pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
				}
				devicelist = devicedao.queryDevicelistPage(pageModel);
			}
			pageModel.setQueryresult(devicelist);
		}
		return pageModel;
	}

	// 新增设备
	@Override
	@Transactional
	public String addDevice(ParamForm paramForm) {
		if (!RegexUtil.checkPrice(paramForm.getFee()) || !RegexUtil.checkPrice(paramForm.getFee2())) {
			return Constant.CHECK_FALSE;
		}
		if (!RegexUtil.checkIMEI(paramForm.getImei())) {
			return Constant.Device.IMEI_FALSE;
		}
		if (!RegexUtil.checkCardId(paramForm.getCardid())) {
			return Constant.Device.CARD_FALSE;
		}
		if (paramForm.getTelephone() != null) {
			if (!Utils.isTel(paramForm.getTelephone())) {
				return Constant.Device.TEL_FALSE;
			}
		}
		// 创建临时表,并添加数据
		createTempTable();
		if (paramForm.getType() != null) {
			String res = null;
			if ("1".equals(paramForm.getType())) {
				res = addSmartDevice1(paramForm);
			} else if ("2".equals(paramForm.getType())) {
				res = addSmartDevice2(paramForm);
			} else {
				res = addCard(paramForm);
			}
			if (!Constant.SUCCESS.equals(res)) {
				return res;
			}
		} else {
			return "类型不能为空";
		}
		return Constant.SUCCESS;
	}

	// 新增卫小宝
	private String addSmartDevice1(ParamForm paramForm) {
		if (StringUtil.isEmpty(paramForm.getImei())) {
			return "设备号不能为空";
		}
		if (paramForm.getImei().length() != 15) {
			return "设备imei号长度不是15位";
		}
		if (StringUtil.isEmpty(paramForm.getBatchid())) {
			return Constant.Device.BATCHID_NOT_NULL;
		}
		if (StringUtil.isEmpty(paramForm.getBoxid())) {
			return Constant.Device.BOXID_NOT_NULL;
		}
		// 如果设备手机号为空，则给设备手机号置为空串,保证新增的时候不报错
		if (StringUtil.isBlank(paramForm.getTelephone())) {
			paramForm.setTelephone("");
		}
		List<DeviceInfo> iotDeviceLists = new ArrayList<>();
		DeviceInfo deviceInfo = new DeviceInfo();
		BigDecimal fee = null, fee2 = null;
		Map<String, Object> map = new HashMap<>();
		int status = 0;
		String factory = null;
		if (paramForm.getSchoolname() == null) {
			status = -1;
		}
		map.put("imei", paramForm.getImei());
		List<DeviceInfo> iotDeviceList = deviceInitdao.queryIotDeviceIsExist(map);
		if (iotDeviceList.size() > 0) {
			return Constant.Device.DEVICE_EXIST;
		}
		Date endtime = getSmartDeviceEndtime(paramForm.getDevicePackage());
		if (endtime == null) {
			return "套餐年限不符合规范";
		}
		if (paramForm.getFee() == null) {
			fee = new BigDecimal("0");
		} else {
			fee = new BigDecimal(paramForm.getFee());
		}
		if (paramForm.getFee2() == null) {
			if(StringUtils.isNotBlank(paramForm.getSchoolname())) {
				fee2 = devicePriceService.getSchoolPackagePrice(paramForm.getSchoolname());
				if(fee2 == null) {
					fee2 = devicePriceService.getDefaultPackagePrice();
				}
			}
		} else {
			fee2 = new BigDecimal(paramForm.getFee2());
		}
		if (StringUtil.isEmpty(paramForm.getFactory())) {
			factory = "卫小宝";
		} else {
			factory = paramForm.getFactory();
		}
		// 校验设备手机号是否存在
		if (StringUtil.isNotEmpty(paramForm.getTelephone())) {
			if (checkTelephoneIsExist(paramForm.getTelephone(), 1)) {
				return "设备手机号已存在";
			}
		}

		deviceInfo.setBatchid(paramForm.getBatchid());
		deviceInfo.setBoxid(ExcelUtil.zeroize(paramForm.getBoxid(), 3));
		deviceInfo.setFee(fee);
		deviceInfo.setFee2(fee2);
		deviceInfo.setEndtime(endtime);
		deviceInfo.setStatus(status);
		deviceInfo.setSchoolname(paramForm.getSchoolname());
		deviceInfo.setImei(paramForm.getImei());
		deviceInfo.setFactory(factory);
		deviceInfo.setTelephone(paramForm.getTelephone());
		iotDeviceLists.add(deviceInfo);
		map.put("iotDeviceList", iotDeviceLists);
		deviceInitdao.addStdIotDevice(map);
		deviceInitdao.addDeviceTmp(map);
		return Constant.SUCCESS;
	}

	/**
	 * <p>
	 * Title: checkTelephoneIsExist
	 * </p>
	 * <p>
	 * 功能描述:判断设备手机号是否已存在数据库表中
	 * </p>
	 * 
	 * @param telephone
	 *            对应的手机号
	 * @param checkType
	 *            1校验std_iot_device表，2校验devicelists表
	 * @return 存在:true,反之false
	 */
	private boolean checkTelephoneIsExist(String telephone, int checkType) {
		if (checkType == 1) {
			StdIotDeviceExample stdIotDeviceExample = new StdIotDeviceExample();
			stdIotDeviceExample.createCriteria().andSimidEqualTo(telephone);
			List<StdIotDevice> devicelist = stdIotDeviceMapper.selectByExample(stdIotDeviceExample);
			if (devicelist != null && devicelist.size() > 0) {
				return true;
			}
		} else {
			DevicelistExample devicelistExample = new DevicelistExample();
			devicelistExample.createCriteria().andTelephoneEqualTo(telephone);
			List<Devicelist> devicelist = devicelistMapper.selectByExample(devicelistExample);
			if (devicelist != null && devicelist.size() > 0) {
				return true;
			}
		}
		return false;
	}

	// 新增赛丰
	private String addSmartDevice2(ParamForm paramForm) {
		if (StringUtil.isEmpty(paramForm.getImei())) {
			return "设备号不能为空";
		}
		if (StringUtil.isEmpty(paramForm.getSchoolname())) {
			return "学校不能为空";
		}
		if (StringUtil.isEmpty(paramForm.getCardid())) {
			return "考勤卡号不能为空";
		}
		Date endtime = getSmartDeviceEndtime(paramForm.getDevicePackage());
		if (endtime == null) {
			return "套餐年限不符合规范";
		}
		String fee = null, fee2 = null;
		List<DeviceInfo> deviceLists = new ArrayList<>();
		DeviceInfo deviceInfo = new DeviceInfo();
		Map<String, Object> map = new HashMap<>();
		if (paramForm.getFee() == null) {
			fee = "0";
		} else {
			fee = paramForm.getFee();
		}
		if (paramForm.getFee2() == null) {
			fee2 = "0";
		} else {
			fee2 = paramForm.getFee2();
		}

		deviceInfo.setEndtime(endtime);
		deviceInfo.setDevicetype(Integer.parseInt(paramForm.getDevicetype()));
		deviceInfo.setFactory(paramForm.getFactory());
		deviceInfo.setFee(new BigDecimal(fee));
		deviceInfo.setFee2(new BigDecimal(fee2));
		deviceInfo.setImei(paramForm.getImei());
		deviceInfo.setSchoolname(paramForm.getSchoolname());
		deviceInfo.setTelephone(paramForm.getTelephone());
		deviceInfo.setCardid(paramForm.getCardid());
		deviceLists.add(deviceInfo);
		map.put("deviceList", deviceLists);
		deviceInitdao.addDeviceList(map);
		deviceInitdao.addDeviceTmp(map);
		return Constant.SUCCESS;
	}

	// 新增考勤卡
	private String addCard(ParamForm paramForm) {
		if (StringUtil.isEmpty(paramForm.getSchoolname())) {
			return "学校不能为空";
		}
		if (StringUtil.isEmpty(paramForm.getCardid())) {
			return "考勤卡号不能为空";
		}
		String factory = null, fee = null, fee2 = null, imei = null, telephone = null, endtime = "2099-12-31 00:00:00";
		List<DeviceInfo> deviceLists = new ArrayList<>();
		DeviceInfo deviceInfo = new DeviceInfo();
		Map<String, Object> map = new HashMap<>();
		if ("3".equals(paramForm.getType())) {
			factory = "13.56";
			imei = new StringBuffer().append(Constant._13_56_MDTID_PREFIX).append(paramForm.getCardid()).toString();
			telephone = new StringBuffer().append(Constant._13_56_TEL_PREFIX).append(paramForm.getCardid()).toString();
			map.put("mdtid",
					new StringBuffer().append(Constant._13_56_MDTID_PREFIX).append(paramForm.getCardid()).toString());
		} else if ("4".equals(paramForm.getType())) {
			factory = "2.4";
			imei = new StringBuffer().append(Constant._2_4G_MDTID_PREFIX).append(paramForm.getCardid()).toString();
			telephone = new StringBuffer().append(Constant._2_4G_TEL_PREFIX).append(paramForm.getCardid()).toString();
			map.put("mdtid",
					new StringBuffer().append(Constant._2_4G_MDTID_PREFIX).append(paramForm.getCardid()).toString());
		} else {
			return "类型不符";
		}
		// 先查询数据库里有无该设备
		List<DeviceInfo> deviceList = deviceInitdao.queryDeviceListIsExist(map);
		if (deviceList.size() > 0) {
			return Constant.Device.DEVICE_EXIST;
		}
		if (paramForm.getFee() == null) {
			fee = "0";
		} else {
			fee = paramForm.getFee();
		}
		if (paramForm.getFee2() == null) {
			fee2 = "0";
		} else {
			fee2 = paramForm.getFee2();
		}

		deviceInfo.setEndtime(DateUtil.formatStringToTime(endtime, "yyyy-MM-dd HH:mm:ss"));
		deviceInfo.setCardid(paramForm.getCardid());
		deviceInfo.setDevicetype(Integer.parseInt(paramForm.getDevicetype()));
		deviceInfo.setFactory(factory);
		deviceInfo.setFee(new BigDecimal(fee));
		deviceInfo.setFee2(new BigDecimal(fee2));
		deviceInfo.setImei(imei);
		deviceInfo.setSchoolname(paramForm.getSchoolname());
		deviceInfo.setTelephone(telephone);
		deviceLists.add(deviceInfo);
		map.put("deviceList", deviceLists);
		deviceInitdao.addDeviceList(map);
		deviceInitdao.addDeviceTmp(map);
		return Constant.SUCCESS;

	}

	private Date getSmartDeviceEndtime(Integer devicePackageType) {
		if (devicePackageType == null) {
			String datetime = DateUtil.getTime(new Date(), DateUtil.DATE, 1);
			String newTime = datetime.split("[ ]")[0] + " 00:00:00";
			return DateUtil.formatStringToTime(newTime, "yyyy-MM-dd HH:mm:ss");
		} else {
			String devicePackage = null;
			if (devicePackageType == 1) {
				devicePackage = "1年";
			} else if (devicePackageType == 2) {
				devicePackage = "2年";
			} else {
				return null;
			}
			return OpUtil.setDevicePackageToEndtime(devicePackage);
		}
	}

	// 修改设备
	@Override
	@Transactional
	public int updateDevice(ParamForm paramForm) {
		Map<String, Object> map = new HashMap<>();
		map.put("imei", paramForm.getImei());
		map.put("factory", paramForm.getFactory());
		map.put("batchid", paramForm.getBatchid());
		map.put("boxid", paramForm.getBoxid());
		map.put("fee", paramForm.getFee());
		map.put("fee2", paramForm.getFee2());
		int result = deviceInitdao.updateDevice(map);
		return result;
	}

	// 删除设备
	@Override
	@Transactional
	public int deleteDevice(int id) {
		int result = deviceInitdao.deleteDevice(id);
		return result;
	}

	// 设备投放
	@Override
	@Transactional
	public void putDevice(DeviceInfo device) {
		if (device == null || StringUtil.isEmpty(device.getSchoolname())) {
			throw new OpServiceException("学校不存在");
		}
		String ids = device.getIds();
		if (ids == null || ids.trim().equals("")) {
			throw new OpServiceException("设备id不符合规范");
		}
		String[] idList = ids.split("[,，]");
		String puttype = device.getPuttype();
		DeviceInfo temp = new DeviceInfo();
		temp.setSchoolname(device.getSchoolname());
		if (StringUtil.isEmpty(device.getPutstatus()) || device.getPutstatus().equals("1")) {
			for (int i = 0; i < idList.length; i++) {
				if (idList[i] != null && !idList[i].trim().equals("")) {
					if ("1".equals(puttype)) {
						temp.setBoxid(idList[i]);
						deviceInitdao.putDeviceByBox(temp);
					} else {
						// 判断当前设备是否已存在于devicelists表中
						DeviceInfo deviceTemp = new DeviceInfo();
						deviceTemp.setId(Integer.parseInt(idList[i]));
						DeviceInfo deviceInfo = deviceInitdao.queryDeviceByID(deviceTemp);
						if (deviceInfo == null) {
							throw new OpServiceException("设备未入库");
						}
						final Integer id = Integer.parseInt(idList[i]);
						temp.setId(id);
						deviceInitdao.putDevice(temp);
						
						BigDecimal fee2 = devicePriceService.getSchoolPackagePrice(device.getSchoolname());
						StdIotDevice stdIotDevice = new StdIotDevice();
						if(fee2 != null) {
							stdIotDevice.setFee2(fee2);
						}else if(deviceInfo.getFee2() == null) {
							stdIotDevice.setFee2(devicePriceService.getDefaultPackagePrice());
						}
						if(stdIotDevice.getFee2() != null) {
							stdIotDevice.setId(id);
							stdIotDeviceMapper.updateByPrimaryKeySelective(stdIotDevice);
						}
						
						Map<String, Object> map = new HashMap<>();
						map.put("imei", deviceInfo.getImei().substring(0, 14));
						List<DeviceInfo> deviceList = devicedao.queryDevice(map);
						// 若devicelists表中存在当前设备，则将学校修改为目标学校
						if (deviceList.size() > 0) {
							if(fee2 != null && (deviceInfo.getFee2() == null || deviceInfo.getFee2().compareTo(new BigDecimal("0")) == 0)) {
								map.put("fee2", fee2);
							}
							map.put("schoolname", device.getSchoolname());
							devicedao.updateDevicelistByImei(map);
						}
					}
				}
			}
		} else {
			Map<String, Object> map = new HashMap<>();
			DeviceInfo deviceInfo = null;
			for (int i = 0; i < idList.length; i++) {
				// 判断当前考勤卡的考勤卡号是否被上次升级的时候删除了，若被删除，则将mdtid号的后10设置为考勤卡号
				deviceInfo = devicedao.queryDeviceById(Integer.parseInt(idList[i]));
				if (StringUtil.isEmpty(deviceInfo.getCardid())
						&& "3".equals(String.valueOf(deviceInfo.getDevicetype()))) {
					map.put("cardid", deviceInfo.getMdtid().substring(4));
				}
				map.put("id", idList[i]);
				map.put("schoolname", device.getSchoolname());
				deviceInitdao.updateDeviceList(map);
			}
		}
	}

	/**
	 * <p>
	 * Title: importDevice
	 * </p>
	 * <p>
	 * 功能描述:设备入库
	 * </p>
	 * 
	 * @param wb
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional
	public String importDevice(HSSFWorkbook wb) throws Exception {
		String[] tableHead = { "生产商", "IMEI", "设备价格", "套餐价格", "批号", "箱号", "考勤卡号", "学校", "设备手机号", "设备套餐" };
		String[] excelTemplate = { Constant.Device.IMEI, Constant.Device.CARDID, Constant.Device.TELEPHONE };
		String checkExcel = ExcelUtil.checkExcel(wb, tableHead, excelTemplate, false);
		if (!Constant.TRUE.equals(checkExcel)) {
			return checkExcel;
		}
		Map<String, String> tableMap = new HashMap<>();
		tableMap.put("factory", "生产商");
		tableMap.put("imei", "IMEI");
		tableMap.put("fee", "设备价格");
		tableMap.put("fee2", "套餐价格");
		tableMap.put("batchid", "批号");
		tableMap.put("boxid", "箱号");
		tableMap.put("cardid", "考勤卡号");
		tableMap.put("schoolname", "学校");
		tableMap.put("telephone", "设备手机号");
		tableMap.put("devicepackage", "设备套餐");
		ExcelUtil excelUtil = new ExcelUtil();
		List<DeviceInfo> deviceLists = excelUtil.getExcelValue(tableMap, wb, DeviceInfo.class);
		DeviceInfo deviceInfo = null;
		Set<String> factorySet = new HashSet<>();
		boolean isWEIXIAOBAO = false;
		for (int i = 0; i < deviceLists.size(); i++) {
			deviceInfo = deviceLists.get(i);
			if (StringUtil.isNotEmpty(deviceInfo.getSchoolname())) {
				deviceInfo.setSchoolname(deviceInfo.getSchoolname().replace(" ", ""));
			}
			if (StringUtil.isNotEmpty(deviceInfo.getFactory())) {
				deviceInfo.setFactory(deviceInfo.getFactory().replace(" ", ""));
				factorySet.add(deviceInfo.getFactory());
				if (Constant.Device.WEIXIAOBAO.equals(deviceInfo.getFactory())) {
					isWEIXIAOBAO = true;
				}
			}
			checkDeviceInfoAsImport(deviceInfo, i);
			if (deviceInfo.getFee() == null) {
				deviceInfo.setFee(new BigDecimal(0));
			}
			if (deviceInfo.getFee2() == null) {
				deviceInfo.setFee2(new BigDecimal(0));
				if(StringUtil.isNotEmpty(deviceInfo.getSchoolname()) && isWEIXIAOBAO) {
					BigDecimal fee2 = devicePriceService.getSchoolPackagePrice(deviceInfo.getSchoolname());
					if(fee2 != null) {
						deviceInfo.setFee2(fee2);
					}else {
						deviceInfo.setFee2(devicePriceService.getDefaultPackagePrice());
					}
				}
			}
			if (Constant.Device.WEIXIAOBAO.equals(deviceInfo.getFactory())) {
				deviceInfo.setDevicetype(2);
				deviceInfo.setBoxid(ExcelUtil.zeroize(deviceInfo.getBoxid(), 3));
				if (StringUtil.isEmpty(deviceInfo.getDevicepackage())) {
					String datetime = DateUtil.getTime(new Date(), DateUtil.DATE, 1);
					String newTime = datetime.split("[ ]")[0] + " 00:00:00";
					deviceInfo.setEndtime(DateUtil.formatStringToTime(newTime, "yyyy-MM-dd HH:mm:ss"));
				} else {
					deviceInfo.setEndtime(OpUtil.setDevicePackageToEndtime(deviceInfo.getDevicepackage()));
				}
				if (StringUtil.isNotEmpty(deviceInfo.getSchoolname())) {
					deviceInfo.setStatus(0);
				} else {
					deviceInfo.setStatus(-1);
				}
			} else if (Constant.Device.WHITE_CARD1.equals(deviceInfo.getFactory())
					|| Constant.Device.WHITE_CARD2.equals(deviceInfo.getFactory())) {
				deviceInfo.setDevicetype(3);
				String datetime = "2099-12-31 00:00:00";
				deviceInfo.setEndtime(DateUtil.formatStringToTime(datetime, "yyyy-MM-dd HH:mm:ss"));
				if (StringUtil.isNotEmpty(deviceInfo.getCardid())) {
					if (Constant.Device.WHITE_CARD2.equals(deviceInfo.getFactory())) {
						deviceInfo.setImei(String.format("8888%s", deviceInfo.getCardid()));
						deviceInfo.setTelephone(String.format("8%s", deviceInfo.getCardid()));
					} else if (Constant.Device.WHITE_CARD1.equals(deviceInfo.getFactory())) {
						deviceInfo.setImei(String.format("9999%s", deviceInfo.getCardid()));
						deviceInfo.setTelephone(String.format("9%s", deviceInfo.getCardid()));
					}
				}
			} else if (Constant.Device.SAIFENG.equals(deviceInfo.getFactory())) {
				if (StringUtil.isEmpty(deviceInfo.getDevicepackage())) {
					String datetime = DateUtil.getTime(new Date(), DateUtil.DATE, 1);
					String newTime = datetime.split("[ ]")[0] + " 00:00:00";
					deviceInfo.setEndtime(DateUtil.formatStringToTime(newTime, "yyyy-MM-dd HH:mm:ss"));
				} else {
					deviceInfo.setEndtime(OpUtil.setDevicePackageToEndtime(deviceInfo.getDevicepackage()));
				}
				deviceInfo.setDevicetype(2);
			}
		}
		if (factorySet.size() > 1) {
			throw new OpServiceException("不能同时导入不同生产商的设备信息");
		}
		// 创建临时表,并添加数据
		createTempTable();
		createRepeatTable();
		int isAdd = importDevice(deviceLists, isWEIXIAOBAO);
		if (isAdd == 1) {
			return Constant.Excel.EXCEL_IS_EXIST;
		} else {
			return Constant.Excel.IMPORT_TRUE;
		}
	}

	private int importDevice(List<DeviceInfo> deviceList, boolean isWEIXIAOBAO) {
		Map<String, Object> map = new HashMap<>();
		if (deviceList.size() > 0) {
			for (int i = 0; i < deviceList.size(); i = i + Constant.Excel.NUM) {
				List<DeviceInfo> tempList = new ArrayList<>();
				if (i + Constant.Excel.NUM >= deviceList.size()) {
					tempList = deviceList.subList(i, deviceList.size());
				} else {
					tempList = deviceList.subList(i, i + Constant.Excel.NUM);
				}
				if (isWEIXIAOBAO) {
					map.put("iotDeviceList", tempList);
				} else {
					map.put("deviceList", tempList);
				}
				deviceInitdao.addDeviceTmp(map);
			}
			if (isWEIXIAOBAO) {
				return deviceInitdao.importStdIotDevice();
			} else {
				return deviceInitdao.importDevicelists();
			}
		}
		return 0;
	}

	private void checkDeviceInfoAsImport(DeviceInfo deviceInfo, int index) {
		if (StringUtil.isNotEmpty(deviceInfo.getSchoolname())) {
			// 查询学校名称是否存在，不存在则无法入库
			SchoolinfoExample schoolinfoExample = new SchoolinfoExample();
			schoolinfoExample.createCriteria().andSchoolnameEqualTo(deviceInfo.getSchoolname());
			List<Schoolinfo> schoolList = schoolinfoMapper.selectByExample(schoolinfoExample);
			if (schoolList.size() == 0) {
				throw new OpServiceException(String.format(failReason, index + 2, "无法找到该学校"));
			}
		}
		if (StringUtil.isEmpty(deviceInfo.getFactory())) {
			throw new OpServiceException(String.format(failReason, index + 2, "生产商为空"));
		}
		if (Constant.Device.WEIXIAOBAO.equals(deviceInfo.getFactory())) {
			if (StringUtil.isEmpty(deviceInfo.getImei())) {
				throw new OpServiceException(String.format(failReason, index + 2, "imei号为空"));
			}
			if (deviceInfo.getImei().length() != 15) {
				throw new OpServiceException(String.format(failReason, index + 2, "imei号长度不是15位"));
			}
			if (StringUtil.isEmpty(deviceInfo.getBatchid())) {
				throw new OpServiceException(String.format(failReason, index + 2, "批号为空"));
			}
			if (StringUtil.isEmpty(deviceInfo.getBoxid())) {
				throw new OpServiceException(String.format(failReason, index + 2, "箱号为空"));
			}
		} else {
			if (StringUtil.isEmpty(deviceInfo.getSchoolname())) {
				throw new OpServiceException(String.format(failReason, index + 2, "学校为空"));
			}
			if (StringUtil.isEmpty(deviceInfo.getCardid())) {
				throw new OpServiceException(String.format(failReason, index + 2, "考勤卡为空"));
			}
		}

		// 判断设备手机号是否已存在，若存在，则无法入库
		if (StringUtil.isNotEmpty(deviceInfo.getTelephone())) {
			if (checkTelephoneIsExist(deviceInfo.getTelephone(), 1)) {
				throw new OpServiceException(String.format(failReason, index + 2, "设备手机号已存在"));
			}
		}
	}

	/**
	 * <p>
	 * Title: createTempTable
	 * </p>
	 * <p>
	 * 功能描述:创建临时表
	 * </p>
	 */
	public void createTempTable() {
		deviceInitdao.createTmpTable();
		Integer isExist = deviceInitdao.queryTempIndex();
		if (isExist == 0) {
			deviceInitdao.addTempIndex();
		}
		deviceInitdao.deleteTmpTable();
	}

	/**
	 * <p>
	 * Title: createRepeatTable
	 * </p>
	 * <p>
	 * 功能描述:创建临时重复表，若数据库里有重复数据，则将重复数据添加到重复表中
	 * </p>
	 */
	public void createRepeatTable() {
		deviceInitdao.createRepeatTable();
		deviceInitdao.deleteRepeatTable();
	}

	/**
	 * <p>
	 * Title: queryDeviceTmp
	 * </p>
	 * <p>
	 * 功能描述:查看最近一次导入数据
	 * </p>
	 * 
	 * @param paramForm
	 * @return
	 */
	@Override
	public PageModel<DeviceVO> queryDeviceTmp(ParamForm paramForm) {
		PageModel<DeviceVO> pageModel = new PageModel<DeviceVO>();
		if (StringUtil.isNotEmpty(paramForm.getPagecount())) {
			pageModel.setPagesize(Integer.parseInt(paramForm.getPagecount()));
		}
		try {
			Integer totleRows = deviceInitdao.queryDeviceTmpRows();
			pageModel.setTotlepage(totleRows);
			if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
				pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
			}
			List<DeviceInfo> deviceList = deviceInitdao.queryDeviceTmp(pageModel);
			DeviceVO device = new DeviceVO();
			pageModel.setQueryresult(device.deviceInfoToVO(deviceList));
		} catch (Exception e) {

		}
		return pageModel;
	}

	/**
	 * <p>
	 * Title: cancelDeviceImport
	 * </p>
	 * <p>
	 * 功能描述:撤销导入数据
	 * </p>
	 * 
	 * @return
	 */
	@Override
	public String cancelDeviceImport() {
		PageModel<DeviceInfo> pageModel = new PageModel<DeviceInfo>();
		pageModel.getQueryparam().put("isNotPage", "1");
		try {
			// 查询卫小宝是否已被使用
			List<DeviceInfo> iotDevices = deviceInitdao.queryIotDeviceTmpIsBind();
			// 查询考勤卡是否已被使用
			List<DeviceInfo> devices = deviceInitdao.queryDeviceListTmpIsBind();
			int isDeleted = 0;
			if (iotDevices.size() > 0) {
				StringBuffer exist = new StringBuffer().append(Constant.Device.DEVICE_IS_BIND);
				for (DeviceInfo deviceInfo : iotDevices) {
					exist.append(deviceInfo.getImei()).append(";");
				}
				return exist.toString();
			} else {
				isDeleted = deviceInitdao.deleteIotDeviceTmpInIotDevice();
			}
			if (isDeleted == 0) {
				if (devices.size() > 0) {
					StringBuffer exist = new StringBuffer().append(Constant.Device.DEVICE_IS_BIND);
					for (DeviceInfo deviceInfo : devices) {
						exist.append(deviceInfo.getMdtid()).append(";");
					}
					return exist.toString();
				} else {
					deviceInitdao.deleteDeviceListTmpInDeviceList();
				}
			}
			// 删除临时表
			deviceInitdao.deleteTmpTable();
		} catch (Exception e) {
			return Constant.Device.ROLLBACK_FAIL;
		}

		return Constant.SUCCESS;
	}

	/**
	 * <p>
	 * Title: queryAllDeviceRows
	 * </p>
	 * <p>
	 * 功能描述:查询全部设备个数
	 * </p>
	 * 
	 * @return
	 */
	@Override
	public int queryAllDeviceRows() {
		return deviceInitdao.countAllRows();
	}

	/**
	 * 查询临时重复表
	 */
	@Override
	public List<DeviceInfo> queryDeviceRepeat() {
		return deviceInitdao.queryRepeatTable();
	}

	/**
	 * <p>
	 * Title: importDeviceReserve
	 * </p>
	 * <p>
	 * 功能描述:导入设备储备
	 * </p>
	 * 
	 * @param wb
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional
	public Object importDeviceReserve(HSSFWorkbook wb, DeviceVO deviceVo) throws Exception {
		if (deviceVo == null || StringUtil.isEmpty(deviceVo.getProvince()) || StringUtil.isEmpty(deviceVo.getCity())
				|| StringUtil.isEmpty(deviceVo.getTown())) {
			return Constant.Device.REGION_NOT_NULL;
		}
		// 校验合法性
		String[] title = { Constant.Device.DEVICETYPE, Constant.Device.CARDID };
		String check = ExcelUtil.checkExcel(wb, title, false);
		if (!Constant.TRUE.equals(check)) {
			return check;
		}
		String[] excelTemplate = { Constant.Device.CARDID };
		String isRepeat = ExcelUtil.checkRepeat(wb, excelTemplate);
		if (!Constant.TRUE.equals(isRepeat)) {
			return isRepeat;
		}

		List<DeviceReserve> deviceList = new LinkedList<>();
		HSSFSheet sheet = wb.getSheetAt(0);
		List<String> indexList = new ArrayList<>();
		HSSFRow titleRow = sheet.getRow(0);
		int rowSize = sheet.getLastRowNum() + 1;
		int colSize = titleRow.getLastCellNum();
		for (int i = 0; i < colSize; i++) {
			titleRow.getCell(i).setCellType(CellType.STRING);
			for (int j = 0; j < title.length; j++) {
				if (titleRow.getCell(i).getRichStringCellValue() != null
						&& title[j].equals(titleRow.getCell(i).getRichStringCellValue().toString())) {
					indexList.add(title[j]);
				}
			}
		}
		String devicetypeIndex = null, cardidIndex = null;
		int indexListSize = indexList.size();
		for (int i = 0; i < indexListSize; i++) {
			if (indexList.get(i).contains(Constant.Device.DEVICETYPE)) {
				devicetypeIndex = String.valueOf(i);
			}
			if (indexList.get(i).contains(Constant.Device.CARDID)) {
				cardidIndex = String.valueOf(i);
			}
		}
		for (int j = 1; j < rowSize; j++) {
			int count = 0;
			// 创建一个行对象
			HSSFRow row = sheet.getRow(j);
			for (int i = 0; i < colSize; i++) {
				HSSFCell cell = row.getCell(i);
				if (cell == null) {
					count++;
					continue;
				}
				row.getCell(i).setCellType(CellType.STRING);
				if (i <= indexListSize) {
					if (row.getCell(i).getRichStringCellValue() == null
							|| !StringUtil.isNotEmpty(row.getCell(i).getRichStringCellValue().toString().trim())) {
						count++;
					}
				}
			}
			if (count >= indexListSize) {
				continue;
			}
			DeviceReserve device = new DeviceReserve();
			String devicetype = null, cardid = null;
			// 设备类型
			if (devicetypeIndex != null && row.getCell(Integer.valueOf(devicetypeIndex)) != null
					&& row.getCell(Integer.valueOf(devicetypeIndex)).getRichStringCellValue() != null
					&& StringUtil.isNotEmpty(
							row.getCell(Integer.valueOf(devicetypeIndex)).getRichStringCellValue().toString())) {
				devicetype = row.getCell(Integer.valueOf(devicetypeIndex)).getRichStringCellValue().toString();
			}
			// cardid
			if (cardidIndex != null && row.getCell(Integer.valueOf(cardidIndex)) != null
					&& row.getCell(Integer.valueOf(cardidIndex)).getRichStringCellValue() != null
					&& StringUtil.isNotEmpty(
							row.getCell(Integer.valueOf(cardidIndex)).getRichStringCellValue().toString())) {
				cardid = row.getCell(Integer.valueOf(cardidIndex)).getRichStringCellValue().toString();
			}

			if (StringUtil.isEmpty(devicetype)) {
				return String.format(failReason, j + 1, "设备类型不能为空");
			}
			if (StringUtil.isEmpty(cardid)) {
				return String.format(failReason, j + 1, "考勤卡不能为空");
			}

			if ("13.56".equals(devicetype)) {
				device.setDevicetype(1);
			} else if ("2.4".equals(devicetype)) {
				device.setDevicetype(2);
			} else {
				return String.format(failReason, j + 1, "设备类型不符");
			}
			device.setCardid(cardid);
			device.setStatus(0);
			device.setProvince(deviceVo.getProvince());
			device.setCity(deviceVo.getCity());
			device.setTown(deviceVo.getTown());
			deviceList.add(device);
		}

		// 将最后一次入库的表示置为0
		DeviceReserve deviceReserve = new DeviceReserve();
		deviceReserve.setIslast(0);
		DeviceReserveExample deviceReserveExample = new DeviceReserveExample();
		deviceReserveExample.createCriteria().andIslastEqualTo(1);
		deviceReserveMapper.updateByExampleSelective(deviceReserve, deviceReserveExample);

		int count = deviceList.size() % Constant.Excel.NUM == 0 ? deviceList.size() / Constant.Excel.NUM
				: deviceList.size() / Constant.Excel.NUM + 1;
		List<DeviceVO> repeatList = new LinkedList<>();
		for (int i = 0; i < count; i++) {
			List<DeviceReserve> tempList = new LinkedList<>();
			for (int j = i * Constant.Excel.NUM; j < (i + 1) * Constant.Excel.NUM; j++) {
				if (j < deviceList.size()) {
					tempList.add(deviceList.get(j));
				}
			}
			// 查询考勤卡是否已入库
			Map<String, Object> map = new HashMap<>();
			map.put("reserveList", tempList);
			List<DeviceReserve> repeatTempList = deviceInitdao.selectDeviceReserve(map);
			List<DeviceInfo> deviceRepeatList = deviceInitdao.queryDeviceListIsExist(map);
			List<DeviceReserve> unRepeatList = new LinkedList<>();
			DeviceVO deviceVoTemp = null;
			for (DeviceReserve deviceTemp : tempList) {
				boolean flag = false;
				if (repeatTempList.size() > 0) {
					for (DeviceReserve repeatTemp : repeatTempList) {
						if (deviceTemp.getCardid().equals(repeatTemp.getCardid())) {
							deviceVoTemp = new DeviceVO();
							deviceVoTemp.setCardid(deviceTemp.getCardid());
							repeatList.add(deviceVoTemp);
							flag = true;
							break;
						}
					}
				}
				if (deviceRepeatList.size() > 0) {
					for (DeviceInfo repeatTemp : deviceRepeatList) {
						if (deviceTemp.getCardid().equals(repeatTemp.getCardid())) {
							deviceVoTemp = new DeviceVO();
							deviceVoTemp.setCardid(repeatTemp.getCardid());
							repeatList.add(deviceVoTemp);
							flag = true;
							break;
						}
					}
				}
				if (flag) {
					continue;
				}
				unRepeatList.add(deviceTemp);
			}
			map = new HashMap<>();
			if (repeatList.size() == 0) {
				map.put("reserveList", tempList);
				deviceInitdao.addDeviceReserve(map);
			} else {
				if (unRepeatList.size() > 0) {
					map.put("reserveList", unRepeatList);
					deviceInitdao.addDeviceReserve(map);
				}
			}
		}
		if (repeatList.size() > 0) {
			return repeatList;
		} else {
			return Constant.SUCCESS;
		}
	}

	/**
	 * <p>
	 * Title: putDeviceReserve
	 * </p>
	 * <p>
	 * 功能描述: 投放储备设备
	 * </p>
	 * 
	 * @param deviceVo
	 * @return
	 */
	@Override
	@Transactional
	public String putDeviceReserve(DeviceVO deviceVo) {
		String[] idArr = deviceVo.getIds().split("[|]");
		DeviceReserveExample deviceReserveExample = new DeviceReserveExample();
		if (idArr.length == 0) {
			return Constant.Device.DEVICEID_NOT_NULL;
		}
		List<Integer> idList = new ArrayList<>();
		for (String id : idArr) {
			idList.add(Integer.parseInt(id));
		}
		deviceReserveExample.createCriteria().andIdIn(idList);
		List<DeviceReserve> deviceReserveList = deviceReserveMapper.selectByExample(deviceReserveExample);

		if (deviceReserveList.size() == 0) {
			return Constant.Device.DEVICEID_FALSE;
		}
		// 查询schoolname
		Schoolinfo schoolInfo = schoolinfoMapper.selectByPrimaryKey(Integer.parseInt(deviceVo.getSchoolid()));
		if (schoolInfo == null) {
			return Constant.Device.SCHOOLID_FALSE;
		}
		if (!deviceVo.getProvince().equals(schoolInfo.getProvince()) || !deviceVo.getCity().equals(schoolInfo.getCity())
				|| !deviceVo.getTown().equals(schoolInfo.getTown())) {
			return "该学校不在此区域，请核实后再投放";
		}
		List<String> cardids = new ArrayList<>();
		for (DeviceReserve deviceReserveTemp : deviceReserveList) {
			cardids.add(deviceReserveTemp.getCardid());
		}
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andCardidIn(cardids);

		List<Devicelist> repeatList = devicelistMapper.selectByExample(devicelistExample);
		List<DeviceInfo> devicelist = new ArrayList<>();
		DeviceInfo devicelistInfo = null;

		for (DeviceReserve deviceReserveTemp : deviceReserveList) {
			boolean flag = false;
			if (repeatList.size() > 0) {
				for (Devicelist deviceTemp : repeatList) {
					if (deviceReserveTemp.getCardid().equals(deviceTemp.getCardid())) {
						flag = true;
						break;
					}
				}
			}
			if (flag) {
				continue;
			}
			devicelistInfo = new DeviceInfo();
			devicelistInfo.setSchoolname(schoolInfo.getSchoolname());
			devicelistInfo.setStatus(0);
			devicelistInfo.setIsinit(false);
			devicelistInfo.setDevicetype(3);
			devicelistInfo.setCardid(deviceReserveTemp.getCardid());
			switch (deviceReserveTemp.getDevicetype()) {
			case 1:
				devicelistInfo.setFactory("13.56");
				devicelistInfo
						.setImei(new StringBuilder().append("8888").append(deviceReserveTemp.getCardid()).toString());
				devicelistInfo
						.setTelephone(new StringBuilder().append("8").append(deviceReserveTemp.getCardid()).toString());
				break;
			case 2:
				devicelistInfo.setFactory("2.4");
				devicelistInfo
						.setImei(new StringBuilder().append("9999").append(deviceReserveTemp.getCardid()).toString());
				devicelistInfo
						.setTelephone(new StringBuilder().append("9").append(deviceReserveTemp.getCardid()).toString());
				break;
			}
			devicelistInfo.setFee(new BigDecimal(0));
			devicelistInfo.setFee2(new BigDecimal(0));
			devicelistInfo.setAddtime(new Date());
			devicelistInfo.setUpdatetime(new Date());
			devicelistInfo.setEndtime(DateUtil.formatStringToTime("2099-12-31 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			devicelist.add(devicelistInfo);

			// 修改device_reserve表
			deviceReserveTemp.setSchoolid(Integer.parseInt(deviceVo.getSchoolid()));
			deviceReserveTemp.setStatus(1);
			deviceReserveMapper.updateByPrimaryKeySelective(deviceReserveTemp);
		}
		// 添加到devicelists表
		Map<String, Object> map = new HashMap<>();
		if (devicelist.size() > 0) {
			map.put("deviceList", devicelist);
			deviceInitdao.addDeviceList(map);
		}
		return Constant.SUCCESS;
	}

	/**
	 * <p>
	 * Title: getDeviceReserveCount
	 * </p>
	 * <p>
	 * 功能描述:获取储备量统计
	 * </p>
	 * 
	 * @param deviceVo
	 * @return
	 */
	@Override
	public PageModel<DeviceVO> getDeviceReserveCount(DeviceVO deviceVo) {
		PageModel<DeviceVO> pageModel = new PageModel<>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("province", deviceVo.getProvince());
		map.put("city", deviceVo.getCity());
		map.put("town", deviceVo.getTown());
		map.put("devicetype", deviceVo.getDevicetype());
		PageQueryModel pqm = new PageQueryModel(deviceVo.getPagenumber(), deviceVo.getPagecount(), null, null);
		pqm.setQueryParam(map);
		PageGrid pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getDeviceReserveCountPage", pqm);
		if (pageGrid == null || pageGrid.getRows().size() == 0) {
			return pageModel;
		}
		BeanUtil<ExtDeviceReserve> beanUtil = new BeanUtil<ExtDeviceReserve>();
		List<ExtDeviceReserve> ents = null;
		try {
			ents = beanUtil.ListMap2JavaBean(pageGrid.getRows(), ExtDeviceReserve.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		List<DeviceVO> deviceList = new ArrayList<>();
		if (ents != null && ents.size() > 0) {
			DeviceVO device = null;
			for (ExtDeviceReserve deviceReserveTemp : ents) {
				device = new DeviceVO();
				device.setProvince(deviceReserveTemp.getProvince());
				device.setCity(deviceReserveTemp.getCity());
				device.setTown(deviceReserveTemp.getTown());
				device.setDevicetype(deviceReserveTemp.getDevicetype() == null ? null
						: String.valueOf(deviceReserveTemp.getDevicetype()));
				device.setTotalcount(deviceReserveTemp.getTotalcount());
				device.setUnputcount(deviceReserveTemp.getUnputcount());
				device.setPutcount(deviceReserveTemp.getPutcount());
				deviceList.add(device);
			}
			pageModel.setPagesize(deviceVo.getPagecount());
			pageModel.setTotlerows(pageGrid.getRecords());
			pageModel.setTotlepage(pageGrid.getRecords());
			pageModel.setCurrentpage(pageGrid.getPage());
		}
		pageModel.setQueryresult(deviceList);
		return pageModel;
	}

	/**
	 * <p>
	 * Title: getDeviceReserves
	 * </p>
	 * <p>
	 * 功能描述:区域储备设备详情
	 * </p>
	 * 
	 * @param deviceVo
	 * @return
	 */
	@Override
	public PageModel<DeviceVO> getDeviceReserves(DeviceVO deviceVo) {
		PageModel<DeviceVO> pageModel = new PageModel<>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("province", deviceVo.getProvince());
		map.put("city", deviceVo.getCity());
		map.put("town", deviceVo.getTown());
		map.put("devicetype", deviceVo.getDevicetype());
		map.put("schoolid", deviceVo.getSchoolid());
		map.put("status", deviceVo.getStatus());
		map.put("islast", deviceVo.getIslast());
		map.put("cardid", deviceVo.getCardid());
		PageQueryModel pqm = new PageQueryModel(deviceVo.getPagenumber(), deviceVo.getPagecount(), "a.status", "asc");
		pqm.setQueryParam(map);
		PageGrid pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getDeviceReservesPage", pqm);
		if (pageGrid == null || pageGrid.getRows().size() == 0) {
			return pageModel;
		}
		BeanUtil<ExtDeviceReserve> beanUtil = new BeanUtil<ExtDeviceReserve>();
		List<ExtDeviceReserve> ents = null;
		try {
			ents = beanUtil.ListMap2JavaBean(pageGrid.getRows(), ExtDeviceReserve.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		List<DeviceVO> deviceList = new ArrayList<>();
		if (ents != null && ents.size() > 0) {
			DeviceVO device = null;
			for (ExtDeviceReserve deviceReserveTemp : ents) {
				device = new DeviceVO();
				device.setDevicetype(deviceReserveTemp.getDevicetype() == null ? null
						: String.valueOf(deviceReserveTemp.getDevicetype()));
				device.setId(deviceReserveTemp.getId() == null ? null : String.valueOf(deviceReserveTemp.getId()));
				device.setCardid(deviceReserveTemp.getCardid());
				device.setStatus(
						deviceReserveTemp.getStatus() == null ? null : String.valueOf(deviceReserveTemp.getStatus()));
				device.setSchoolname(deviceReserveTemp.getSchoolname());
				deviceList.add(device);
			}
			pageModel.setPagesize(deviceVo.getPagecount());
			pageModel.setTotlerows(pageGrid.getRecords());
			pageModel.setTotlepage(pageGrid.getRecords());
			pageModel.setCurrentpage(pageGrid.getPage());
		}
		pageModel.setQueryresult(deviceList);
		return pageModel;
	}

	@Override
	@Transactional
	public String cancelLastImport() {
		// 先查询最后一次入库的设备是否已经投放，若有投放的设备，则无法撤销
		Map<String, String> queryParam = new HashMap<String, String>();
		queryParam.put("status", "1");
		queryParam.put("islast", "1");
		queryParam.put("RESULT_COUNT", PageQueryModel.COUNT_ALL_NAME);
		queryParam.put("doCount", "true");
		Map result = (Map) commonService.selectOne("OpDeviceExtendSql.getDeviceReservesPage", queryParam);
		int records = Integer.parseInt(result.get(PageQueryModel.COUNT_ALL_NAME).toString());
		if (records > 0) {
			return new StringBuilder().append(Constant.Device.CANCEL_FALSE).append(",")
					.append(Constant.Device.DEVICE_IS_PUT).toString();
		}
		// 撤销最后一次入库
		DeviceReserveExample deviceReserveExample = new DeviceReserveExample();
		deviceReserveExample.createCriteria().andIslastEqualTo(1);
		deviceReserveMapper.deleteByExample(deviceReserveExample);
		return Constant.SUCCESS;
	}

	/**
	 * <p>
	 * Title: recycleDevice
	 * </p>
	 * <p>
	 * 功能描述:回收设备
	 * </p>
	 * 
	 * @param deviceVo
	 * @return
	 */
	@Override
	@Transactional
	public void recycleDevice(ParamForm paramForm) {
		List<String> imeiList = StringUtil.StringToStringList(paramForm.getImei(), "[,，]");
		checkRecycleDevice(imeiList, paramForm.getType());
		Map<String, Object> map = new HashMap<>();
		// 回收卫小宝
		if ("1".equals(paramForm.getType())) {
			map.put("imeiList", imeiList);
			// 将设备的status置为-1，schoolname置为null
			deviceInitdao.recycleIotDeviceByImei(map);
			// 判断卫小宝是否进入devicelists表，若是，则清除对应的学校信息
			for (String imei : imeiList) {
				map = new HashMap<>();
				map.put("imei", imei.substring(0, 14));
				List<DeviceInfo> deviceList = devicedao.queryDevice(map);
				if (deviceList.size() > 0) {
					devicedao.deleteDeviceLists(imei.substring(0, 14));
				}
				//将设备的套餐价设置为默认价
				DevicelistExample devicelistExample = new DevicelistExample();
				devicelistExample.createCriteria().andMdtidEqualTo(imei.substring(0, 14));
				Devicelist devicelist2 = new Devicelist();
				devicelist2.setFee2(devicePriceService.getDefaultPackagePrice());
				devicelistMapper.updateByExampleSelective(devicelist2, devicelistExample);

				StdIotDeviceExample stdIotDeviceExample = new StdIotDeviceExample();
				stdIotDeviceExample.createCriteria().andImeiEqualTo(imei);
				StdIotDevice stdIotDevice = new StdIotDevice();
				stdIotDevice.setFee2(devicePriceService.getDefaultPackagePrice());
				stdIotDevice.setSchoolname("");
				stdIotDeviceMapper.updateByExampleSelective(stdIotDevice, stdIotDeviceExample);
				
				// 回收实名认证
				StdIotDeviceExample deviceExample = new StdIotDeviceExample();
				deviceExample.createCriteria().andImeiEqualTo(imei);
				List<StdIotDevice> listDevice = stdIotDeviceMapper.selectByExample(deviceExample);
				if (listDevice != null && !listDevice.isEmpty()) {
					StdIotDevice iotDevice = listDevice.get(0);
					// stdIotDeviceMapper.deleteByExample(deviceExample);

					StdSimidauthExample authExample = new StdSimidauthExample();
					authExample.createCriteria().andSimidEqualTo(iotDevice.getSimid());
					stdSimidauthMapper.deleteByExample(authExample);

					PurchaseDeliveryExample deliveryExample = new PurchaseDeliveryExample();
					deliveryExample.createCriteria().andMdtidEqualTo(imei);
					purchaseDeliveryMapper.deleteByExample(deliveryExample);
				}

				
				//判断设备是否已经解绑过的，若解绑过，则需要将std_deviceinfo的数据置为逻辑删除
				StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
				stdDeviceinfoExample.createCriteria().andMdtidEqualTo(imei).andObjectidEqualTo(0).andPeopleidEqualTo(0);
				StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
				stdDeviceinfo.setIsdeleted(1);
				stdDeviceinfo.setUpdatetime(new Date());
				stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo, stdDeviceinfoExample);
			}
			// 回收其他
		} else {
			for (String imei : imeiList) {
				devicedao.deleteDeviceLists(imei);
				//判断设备是否已经解绑过的，若解绑过，则需要将std_deviceinfo的数据置为逻辑删除
				StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
				stdDeviceinfoExample.createCriteria().andMdtidEqualTo(imei).andObjectidEqualTo(0).andPeopleidEqualTo(0);
				StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
				stdDeviceinfo.setIsdeleted(1);
				stdDeviceinfo.setUpdatetime(new Date());
				stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo, stdDeviceinfoExample);
			}
		}
	}

	/**
	 * 检查回收设备是否符合回收标准
	 * 
	 * @param imeiList
	 * @param type
	 */
	private void checkRecycleDevice(List<String> imeiList, String type) {
		if (imeiList == null || imeiList.size() == 0) {
			throw new OpServiceException("设备imei号不符合规范");
		}
		if (StringUtil.isEmpty(type)) {
			throw new OpServiceException("回收类型不能为空");
		}
		// 回收卫小宝
		if ("1".equals(type)) {
			checkRecycleDeviceByWEIXIAOBAO(imeiList);
		} else {
			Map<String, Object> map = null;
			for (String imei : imeiList) {
				// 判断imei的长度是否是14位
				if (!imei.matches("^[0-9]{14}$")) {
					throw new OpServiceException(String.format("imei号为%s的设备不符合规范", imei));
				}
				map = new HashMap<>();
				map.put("imei", imei);
				List<DeviceInfo> deviceList = devicedao.queryDevice(map);
				if (deviceList.size() == 0) {
					throw new OpServiceException(String.format("imei号为%s的设备不存在", imei));
				}
				checkDeviceStatusByRecycle(getDeviceStatus(imei), imei);
			}
		}
	}

	/**
	 * 检查设备状态是否符合回收标准
	 * 
	 * @param status
	 * @param imei
	 */
	private void checkDeviceStatusByRecycle(int status, String imei) {
		if (status != 0 && status != 1) {
			switch (status) {
			case 2:
				throw new OpServiceException(String.format("imei号为%s的设备已激活，不能回收", imei));
			case 3:
				throw new OpServiceException(String.format("imei号为%s的设备已缴费，不能回收", imei));
			case 4:
				throw new OpServiceException(String.format("imei号为%s的设备已过期，不能回收", imei));
			case 5:
				throw new OpServiceException(String.format("imei号为%s的设备未投放", imei));
			}
		}
	}

	/**
	 * 检查卫小宝
	 * 
	 * @param imeiList
	 */
	private void checkRecycleDeviceByWEIXIAOBAO(List<String> imeiList) {
		DeviceInfo deviceInfo = null;
		for (String imei : imeiList) {
			// 判断imei的长度是否是15位
			if (!imei.matches("^[0-9]{15}$")) {
				throw new OpServiceException(String.format("imei号为%s的设备不符合规范", imei));
			}
			// 判断卫小宝的投放状态
			deviceInfo = new DeviceInfo();
			deviceInfo.setImei(imei);
			DeviceInfo deviceTemp = deviceInitdao.queryDeviceByName(deviceInfo);
			if (deviceTemp == null) {
				throw new OpServiceException(String.format("imei号为%s的设备不存在", imei));
			}
			if (deviceTemp.getStatus() != null && deviceTemp.getStatus() == -1) {
				throw new OpServiceException(String.format("imei号为%s的设备未投放", imei));
			}
			// 判断该设备是否已使用，若已使用，判断设备的状态是否是未激活状态
			checkDeviceStatusByRecycle(getDeviceStatus(imei), imei);
		}
	}

	/**
	 * 获取设备在devicelists表中的状态
	 * 
	 * @param imei
	 * @return
	 */
	private int getDeviceStatus(String imei) {
		Map<String, Object> map = new HashMap<>();
		map.put("status", 3);
		map.put("imei", imei.substring(0, 14));
		PageQueryModel pqm = null;
		PageGrid pageGrid = null;
		pqm = new PageQueryModel(1, 1, null, null);
		pqm.setQueryParam(map);
		int status = 0;
		pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getPaymentPage", pqm);
		if (pageGrid != null && pageGrid.getRows() != null && pageGrid.getRows().size() > 0) {
			status = 3;
		}
		if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
			map.put("status", 2);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getActivePage", pqm);
			if (pageGrid != null && pageGrid.getRows() != null && pageGrid.getRows().size() > 0) {
				status = 2;
			}
			if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
				map.put("status", 1);
				pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getInActivePage", pqm);
				if (pageGrid != null && pageGrid.getRows() != null && pageGrid.getRows().size() > 0) {
					status = 1;
				}
				if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
					map.put("status", 5);
					pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getRecyclePage", pqm);
					if (pageGrid != null && pageGrid.getRows() != null && pageGrid.getRows().size() > 0) {
						status = 5;
					}
					if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
						map.put("status", 4);
						pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getExpirePage", pqm);
						if (pageGrid != null && pageGrid.getRows() != null && pageGrid.getRows().size() > 0) {
							status = 4;
						}
					}
				}
			}
		}
		return status;
	}
}
